<script setup lang="ts">
/**
 * @用途
 * @author bear
 * @创建时间 2025/11/17
 **/
import type { BookmarkDTO, FolderNode } from '@/stores/bookmarkManager'
import { WINDOW_STYLE_CONSTANTS } from '~shared/constants/layout'

const props = defineProps<{
  node: FolderNode
  pos: { x: number; y: number }
  index: number
}>()
const emit = defineEmits<{
  (e: 'opened'): void
  (e: 'ondrop', val: { source: FolderNode | BookmarkDTO; target: FolderNode | BookmarkDTO }): void
  (e: 'enter', val: { node: FolderNode; event: MouseEvent }): void
  (e: 'leave', node: FolderNode): void
}>()
const width = 300
const mh = window.innerHeight - 20
const listRef = ref<any>(null)
const list = computed(() => {
  return [...props.node.bookmarks, ...props.node.children].sort((a, b) => {
    const ai = a.sort ?? Number.MAX_SAFE_INTEGER
    const bi = b.sort ?? Number.MAX_SAFE_INTEGER
    return ai - bi
  }) as any[]
})
const style = computed(() => {
  const barHeight = WINDOW_STYLE_CONSTANTS.TOP_HEIGHT - WINDOW_STYLE_CONSTANTS.SEARCH_BAR_HEIGHT,
    windowHeight = window.innerHeight - barHeight
  const listHeight = listRef.value?.$el.clientHeight || 0
  const y =
    props.pos.y + listHeight > windowHeight
      ? windowHeight - listHeight - 10
      : props.pos.y - barHeight

  return {
    left: `${width * (props.index + 1)}px`,
    top: `${y}px`,
    maxHeight: mh + 'px'
  }
})
</script>

<template>
  <div class="position-absolute menu-box" :style="style">
    <v-list
      ref="listRef"
      class="bg-background"
      density="compact"
      slim
      transition="slide-x-reverse-transition"
      :width="width"
    >
      <template v-for="n in list" :key="n._id">
        <book-item
          v-if="n.link"
          :node="n"
          @ondrop="emit('ondrop', $event)"
          @opened="emit('opened')"
        />
        <folder-item
          v-else
          :node="n"
          @enter="emit('enter', $event)"
          @ondrop="emit('ondrop', $event)"
        />
      </template>
    </v-list>
  </div>
</template>

<style scoped>
.menu-box {
  overflow-y: auto;
}

.menu-box::-webkit-scrollbar {
  width: 0;
}
</style>
